# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(gplots)
library(Hmisc)
library(optparse)
library(ropls)
library(magrittr)
library(ComplexHeatmap)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  filter(ClassNote == "QC") %>%
  as.data.frame()

allData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  left_join(sampleInfo, by = c("SampleID"))

head(allData)

method <- "pearson"
methodStr <- "Pearson"

parent <- "./"
classNote <- "QC"
fileName <- str_c(parent, "/QC_", methodStr, "_Correlation_Heatmap.pdf")
data <- allData %>%
  filter(ClassNote == classNote) %>%
  column_to_rownames("SampleID") %>%
  select(-c("ClassNote"))

print("=data=")
data

corRs <- rcorr(as.matrix(t(data)), type = method)
corData <- corRs$r %>%
  as.data.frame()
write.csv(corData, str_c(parent, "/QC_", methodStr, "_r_values.csv"), col.names = NA, quote = FALSE)

print("=P=")
corRs$P

pData <- corRs$P %>%
  as.data.frame()
write.csv(pData, str_c(parent, "/QC_", methodStr, "_P_values.csv"), col.names = NA, quote = FALSE)

colors <- rev(colorRampPalette(RColorBrewer::brewer.pal(10, "RdBu"))(256))

plotData <- corData

colNum <- ncol(plotData)
width <- 6 + max(0, colNum - 20) * 0.1
rowNum <- nrow(plotData)
height <- max(2 + (rowNum - 10) * 0.1, 2) + 2
pdf(fileName, width = width, height = height)

tryCatch({
  htList <- Heatmap(plotData, col = colors, show_column_names = T, cluster_rows = T, cluster_columns = T,
                    name = "r_value", top_annotation = NULL, right_annotation = NULL,
                    row_names_gp = gpar(fontsize = 9, fontfamily = "Times"),
                    heatmap_legend_param = list(title_gp = gpar(fontsize = 12, fontfamily = "Times"), grid_height = unit(6, "mm"),
                                                labels_gp = gpar(fontsize = 12, fontfamily = "Times")), show_row_names = T,
                    column_names_gp = gpar(fontsize = 9, fontfamily = "Times"), column_title = "",
  )
  draw(htList, heatmap_legend_side = "right", annotation_legend_side = "top",
       padding = unit(c(0.5, 0.5, 0.5, 0.5), "cm")
  )
}, error = function(e) {
  plot(1, type = "n", xlab = "", ylab = "", main = "error:r values are all the same!")
})


dev.off()

